<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Quotation extends MX_Controller {
    
  function __construct() {
    $this->menu = $this->cek();
    $this->load->library('mypdf');
  }
	
	public function index(){
    if($this->input->post()){
      if($this->input->post('cari') == 's'){
        $session_cari = array(
            "crm_quotation_search_title"        => $this->input->post("s_title"),
            "crm_quotation_search_up_to"        => $this->input->post("s_up_to"),
            "crm_quotation_search_date1"        => $this->input->post("s_date1"),
            "crm_quotation_search_date2"        => $this->input->post("s_date2"),
            "crm_quotation_search_telphone"     => $this->input->post("s_telphone"),
        );
        if(!$session_cari['crm_quotation_search_date2'])
          $session_cari['crm_quotation_search_date2'] = $session_cari['crm_quotation_search_date1'];
        
        $this->session->set_userdata($session_cari);
      }
      else{
        $session_cari = array(
            "crm_quotation_search_title"        => "",
            "crm_quotation_search_up_to"        => "",
            "crm_quotation_search_date1"            => "",
            "crm_quotation_search_date2"            => "",
            "crm_quotation_search_telphone"     => "",
        );
        $this->session->unset_userdata($session_cari);
      }
      redirect("crm/quotation");
    }
    
    $where = "WHERE 1 = 1 ";
    if($this->session->userdata("crm_quotation_search_title"))
      $where .= "AND LOWER(B.title) LIKE '%".strtolower($this->session->userdata("crm_quotation_search_title"))."%' ";
    
    if($this->session->userdata("crm_quotation_search_up_to"))
      $where .= "AND LOWER(A.up_to) LIKE '%".strtolower($this->session->userdata("crm_quotation_search_up_to"))."%' ";
    
    if($this->session->userdata("crm_quotation_search_telphone"))
      $where .= "AND LOWER(A.telphone) LIKE '%".strtolower($this->session->userdata("crm_quotation_search_telphone"))."%' ";
    
    if($this->session->userdata("crm_quotation_search_date1")){
      $where .= "
        AND (A.create_date BETWEEN '{$this->session->userdata("crm_quotation_search_date1")}' AND '{$this->session->userdata("crm_quotation_search_date2")}') 
        ";
    }
    
    $total = $this->global_models->get_query("
      SELECT count(A.id_crm_quotation) AS jumlah
      FROM crm_quotation AS A
      LEFT JOIN crm_market_target AS B ON A.id_crm_market_target = B.id_crm_market_target
      {$where}
      ");
      
    $this->template->build("quotation/main",
      array(
            'url'         => base_url()."themes/".DEFAULTTHEMES."/",
            'menu'        => 'crm/quotation',
            'title'       => lang("quotation"),
            'total'       => $total[0]->jumlah
          ));
    $this->template
      ->set_layout('default')
      ->build("quotation/main");
	}
	
	public function history_market_target(){
    if($this->input->post()){
      if($this->input->post('cari') == 's'){
        $session_cari = array(
            "crm_market_target_search_title"        => $this->input->post("s_title"),
            "crm_market_target_search_up_to"        => $this->input->post("s_up_to"),
            "crm_market_target_search_email"        => $this->input->post("s_email"),
            "crm_market_target_search_telphone"     => $this->input->post("s_telphone"),
        );
        $this->session->set_userdata($session_cari);
      }
      else{
        $session_cari = array(
            "crm_market_target_search_title"        => "",
            "crm_market_target_search_up_to"        => "",
            "crm_market_target_search_email"        => "",
            "crm_market_target_search_telphone"     => "",
        );
        $this->session->unset_userdata($session_cari);
      }
      redirect("crm/master-market-target");
    }
    
    $where = "WHERE 1 = 1 ";
    if($this->session->userdata("crm_market_target_search_title"))
      $where .= "AND LOWER(title) LIKE '%".strtolower($this->session->userdata("crm_market_target_search_title"))."%' ";
    
    if($this->session->userdata("crm_market_target_search_up_to"))
      $where .= "AND LOWER(up_to) LIKE '%".strtolower($this->session->userdata("crm_market_target_search_up_to"))."%' ";
    
    if($this->session->userdata("crm_market_target_search_email"))
      $where .= "AND LOWER(email) LIKE '%".strtolower($this->session->userdata("crm_market_target_search_email"))."%' ";
    
    if($this->session->userdata("crm_market_target_search_telphone"))
      $where .= "AND LOWER(telphone) LIKE '%".strtolower($this->session->userdata("crm_market_target_search_telphone"))."%' ";
    
    $total = $this->global_models->get_query("
      SELECT count(id_crm_market_target) AS jumlah
      FROM crm_market_target
      {$where}
      ");
    $this->template->build("history-market-target",
      array(
            'url'         => base_url()."themes/".DEFAULTTHEMES."/",
            'menu'        => 'crm/master-market-target',
            'title'       => lang("master_market_target"),
            'total'       => $total[0]->jumlah
          ));
    $this->template
      ->set_layout('default')
      ->build("history-market-target");
	}
	
  public function ajax_list($field, $sort, $total = 0, $start = 0){
    
    $where = "WHERE 1 = 1 ";
    if($this->session->userdata("crm_quotation_search_title"))
      $where .= "AND LOWER(B.title) LIKE '%".strtolower($this->session->userdata("crm_quotation_search_title"))."%' ";
    
    if($this->session->userdata("crm_quotation_search_up_to"))
      $where .= "AND LOWER(A.up_to) LIKE '%".strtolower($this->session->userdata("crm_quotation_search_up_to"))."%' ";
    
    if($this->session->userdata("crm_quotation_search_telphone"))
      $where .= "AND LOWER(A.telphone) LIKE '%".strtolower($this->session->userdata("crm_quotation_search_telphone"))."%' ";
    
    if($this->session->userdata("crm_quotation_search_date1")){
      $where .= "
        AND (A.create_date BETWEEN '{$this->session->userdata("crm_quotation_search_date1")}' AND '{$this->session->userdata("crm_quotation_search_date2")}') 
        ";
    }
    
    $data = $this->global_models->get_query("
      SELECT A.*, B.title
      FROM crm_quotation AS A
      LEFT JOIN crm_market_target AS B ON A.id_crm_market_target = B.id_crm_market_target
      {$where}
      ORDER BY {$field} {$sort} LIMIT {$start},10
      ");
    
    foreach ($data as $key => $value) {
      
      print "
      <tr class='ajax-quotation'>
        <td>{$value->title}</td>
        <td>{$value->up_to}</td>
        <td>{$value->telphone}</td>
        <td>".date("Y-m-d", strtotime($value->create_date))."</td>
        <td style='text-align: right'>".  number_format($value->total, 0, ",", ".")."</td>
        <td>
          <div class='btn-group'>
            <button data-toggle='dropdown' class='btn btn-small dropdown-toggle'>Action<span class='caret'></span></button>
            <ul class='dropdown-menu'>
              <li><a href='".site_url("crm/quotation/add-new/".$value->id_crm_quotation)."'>Edit</a></li>
              <li><a href='".site_url("crm/quotation/delete-quotation/".$value->id_crm_quotation)."'>Delete</a></li>
            </ul>
          </div>
        </td>
      </tr>";
        
    }
    
    $this->load->library('pagination');

    $config['base_url'] = '';
    $config['total_rows'] = $total;
    $config['per_page'] = 10; 
    $config['uri_segment'] = 7; 
    $config['cur_tag_open'] = "<li class='active'><a href='javascript:void(0)'>"; 
    $config['cur_tag_close'] = "</a></li>"; 
    $config['first_tag_open'] = "<li>"; 
    $config['first_tag_close'] = "</li>"; 
    $config['last_tag_open'] = "<li>"; 
    $config['last_tag_close'] = "</li>"; 
    $config['next_tag_open'] = "<li>"; 
    $config['next_tag_close'] = "</li>"; 
    $config['prev_tag_open'] = "<li>"; 
    $config['prev_tag_close'] = "</li>"; 
    $config['num_tag_open'] = "<li>"; 
    $config['num_tag_close'] = "</li>";
    $config['function_js'] = "load_quotation";

    $this->pagination->initialize($config); 
    print "
    <tr class='ajax-quotation'>
      <td colspan='6'>
        <div class='pagination'>
          <ul>
          ".$this->pagination->create_links_ajax()."
          </ul>
        </div>
      </td>
    </tr>";
    die;
  }
  
  function delete_topic($nicename){
    $this->global_models->delete("d_forum_topic", array("nicename" => $nicename));
    redirect("forum");
  }
  
  public function add_new($id_crm_quotation = 0){
    /**
     * status quotation
     * 1 send
     * 
     * status quotation products
     * 1 active
     * 2 no-active
     * 
     */
    if($this->input->post()){
      $pst = $this->input->post();
      if($pst['id_detail']){
        $kirim = array(
            "title"             => $pst['title'],
            "up_to"             => $pst['up_to'],
            "email"             => $pst['email'],
            "telphone"          => $pst['telphone'],
            "fax"               => $pst['fax'],
            "note"              => $pst['note'],
            "update_by_users"   => $this->session->userdata("id"),
        );
        $id_crm_market_target = $this->global_models->update("crm_market_target", array("id_crm_market_target" => $pst['id_detail']), $kirim);
      }
      else{
        $kirim = array(
            "id_crm_market_target"  => $pst['id_crm_market_target'],
            "up_to"                 => $pst['up_to'],
            "telphone"              => $pst['telphone'],
            "email"                 => $pst['email'],
            "note"                  => $pst['note'],
            "status"                => 1,
            "create_by_users"       => $this->session->userdata("id"),
            "create_date"           => date("Y-m-d H:i:s")
        );
        $id_crm_quotation = $this->global_models->insert("crm_quotation", $kirim);
      }
      if($id_crm_quotation){
        foreach($pst['id_crm_products'] as $k_pp => $id_crm_products){
          $total_price = ($pst['qty'][$k_pp] * $pst['price'][$k_pp]) - (($pst['qty'][$k_pp] * $pst['price'][$k_pp]) * $pst['discount'][$k_pp]/100);
          $kirim_products = array(
              "id_crm_quotation_products" => $pst["id_crm_quotation_products"][$k_pp],
              "id_crm_products"           => $id_crm_products,
              "id_crm_quotation"          => $id_crm_quotation,
              "qty"                       => $pst['qty'][$k_pp],
              "price"                     => $pst['price'][$k_pp],
              "discount"                  => $pst['discount'][$k_pp],
              "total"                     => $total_price,
              "status"                    => 1,
              "note"                      => $pst['product_spesifikasi'][$k_pp],
              "create_by_users"           => $this->session->userdata("id"),
              "create_date"               => date("Y-m-d H:i:s")
          );
          $this->global_models->insert("crm_quotation_products", $kirim_products);
          $total_all += $total_price;
        }
        $this->global_models->update("crm_quotation", array("id_crm_quotation" => $id_crm_quotation), array("total" => $total_all));
        redirect ("crm/quotation/index/1/Berhasil");
      }
      else
        redirect ("crm/quotation/index/2/Gagal");
    }
    else{
      $detail = $this->global_models->get_query("
        SELECT A.*, B.title AS target_market
        FROM crm_quotation AS A
        LEFT JOIN crm_market_target AS B ON A.id_crm_market_target = B.id_crm_market_target
        WHERE A.id_crm_quotation = {$id_crm_quotation}
        ");
      
      if($detail[0]->id_crm_quotation > 0){
        $no = 1;
        $q_items = $this->global_models->get_query("
          SELECT A.*, B.title AS products
          FROM crm_quotation_products AS A
          LEFT JOIN crm_products AS B ON A.id_crm_products = B.id_crm_products
          WHERE A.id_crm_quotation = {$detail[0]->id_crm_quotation}
          ");
        foreach($q_items AS $qi){
          $tr[] = 'tr_'.$no;
          $isi[] = array(
            $this->form_eksternal->form_autocomplate("product[]", "id_crm_products[]", "product_1", "id_crm_products_1", site_url("crm/auto-products"), 
            $qi->products, $qi->id_crm_products,"", "auto_field_items(ui.item.id, 1);"),
            $this->form_eksternal->form_textarea("product_spesifikasi[]", $qi->note, 'style="height: 30px"'),
            $this->form_eksternal->form_input("qty[]", $qi->qty, "onblur='total_price(1)' id='qty_1' style='width: 20px'"),
            $this->form_eksternal->form_input("price[]", $qi->price, "onblur='total_price(1)' id='price_1' style='width: 100px'"),
            $this->form_eksternal->form_input("discount[]", $qi->discount, "onblur='total_price(1)' id='discount_1' style='width: 100px'"),
            "<div id='total_1' style='width:100%;text-align:right;'>".number_format($qi->total, 0, ",", ".")."</div>",
          );
          $no++;
        }
      }
      else{
        
        $tr[] = 'tr_1';
        $isi[] = array(
          $this->form_eksternal->form_autocomplate("product[]", "id_crm_products[]", "product_1", "id_crm_products_1", site_url("crm/auto-products"), 
          "", 0,"", "auto_field_items(ui.item.id, 1);"),
          $this->form_eksternal->form_textarea("product_spesifikasi[]", '', 'style="height: 30px"'),
          $this->form_eksternal->form_input("qty[]", "", "onblur='total_price(1)' id='qty_1' style='width: 20px'"),
          $this->form_eksternal->form_input("price[]", "", "onblur='total_price(1)' id='price_1' style='width: 100px'"),
          $this->form_eksternal->form_input("discount[]", "", "onblur='total_price(1)' id='discount_1' style='width: 100px'"),
          "<div id='total_1' style='width:100%;text-align:right;'>0</div>",
        );
      }
      $this->template->build("quotation/add-new",
        array(
              'url'         => base_url()."themes/".DEFAULTTHEMES."/",
              'menu'        => 'crm/quotation',
              'title'       => lang("quotation"),
              'detail'      => $detail,
              'isi'         => $isi,
              'tr'          => $tr,
            ));
      $this->template
        ->set_layout('default')
        ->build("quotation/add-new");
    }
	}
  
  function auto_field(){
    $id_crm_market_target = $this->input->post("id");
    $data = $this->global_models->get("crm_market_target", array("id_crm_market_target" => $id_crm_market_target));
    $hasil = array(
        "users"     => $data[0]->up_to,
        "email"     => $data[0]->email,
        "telphone"  => $data[0]->telphone,
    );
    print json_encode($hasil);
    die;
  }
  
  function add_products(){
    $no = $this->input->post("no");
    $hasil = "
      <tr id='tr_{$no}'>
        <td valign='top'>".$this->form_eksternal->form_autocomplate("product[]", "id_crm_products[]", "product_{$no}", "id_crm_products_{$no}", site_url("crm/auto-products"), "", 0,"", "auto_field_items(ui.item.id, {$no});")."</td>
        <td valign='top'>".$this->form_eksternal->form_textarea("product_spesifikasi[]", '', 'style="height: 30px"')."</td>
        <td valign='top'>".$this->form_eksternal->form_input("qty[]", "", "onblur='total_price({$no})' id='qty_{$no}' style='width: 20px'")."</td>
        <td valign='top'>".$this->form_eksternal->form_input("price[]", "", "onblur='total_price({$no})' id='price_{$no}' style='width: 100px'")."</td>
        <td valign='top'>".$this->form_eksternal->form_input("discount[]", "", "onblur='total_price({$no})' id='discount_{$no}' style='width: 100px'")."</td>
        <td valign='top'><div id='total_{$no}' style='width:100%;text-align:right;'>0</div></td>
     ";
    $hasil .= <<<EOD
        <td><a href='javascript:void(0)' class='remove-element' onclick='del_row_lokal("tr_{$no}")' title="Remove">Remove</a></td>
      </tr>
EOD;
    print $hasil;die;
  }
  
  function pdf_quotation($id_penawaran){
    $penawaran = $this->global_models->get_query("
      SELECT A.*, B.title
      FROM crm_quotation AS A
      LEFT JOIN crm_market_target AS B ON A.id_crm_market_target = B.id_crm_market_target
      WHERE A.id_crm_quotation = $id_penawaran
    ");
    $items = $this->global_models->get_query("
      SELECT A.*
      FROM crm_quotation_products AS A
      WHERE A.id_crm_quotation = {$id_penawaran}
        AND status = 1");
    
    $this->mypdf->SetCreator(PDF_CREATOR);
    $this->mypdf->SetAuthor('Nugroho B Santoso');
    $this->mypdf->SetTitle('NUSATO for MWM');
    $this->mypdf->SetSubject('Penawaran Harga');
    $this->mypdf->SetKeywords('penawaran, nusato, nugroho, system, pdf');

    // set default header data
//    $this->tcpdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 001', PDF_HEADER_STRING, array(0,64,255), array(0,64,128));
    $this->mypdf->SetHeaderData("img/width-logo2.png", 55, "", "", array(0,64,255), array(0,64,128));
//    $this->mypdf->setFooterData(array(0,64,0), array(0,64,128));

    // set header and footer fonts
    $this->mypdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
    $this->mypdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

    // set default monospaced font
    $this->mypdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

    // set margins
    $this->mypdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
    $this->mypdf->SetHeaderMargin(1);
    $this->mypdf->SetFooterMargin(PDF_MARGIN_FOOTER);

    // set auto page breaks
    $this->mypdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

    // set image scale factor
    $this->mypdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

    // set some language-dependent strings (optional)
    if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
      require_once(dirname(__FILE__).'/lang/eng.php');
      $this->mypdf->setLanguageArray($l);
    }

    // ---------------------------------------------------------

    // set default font subsetting mode
    $this->mypdf->setFontSubsetting(true);

    // Set font
    // dejavusans is a UTF-8 Unicode font, if you only need to
    // print standard ASCII chars, you can use core fonts like
    // helvetica or times to reduce file size.
    $this->mypdf->SetFont('dejavusans', '', 10, '');

    // Add a page
    // This method has several options, check the source code documentation for more information.
    $this->mypdf->AddPage();

    // set text shadow effect
    $this->mypdf->setTextShadow(array('enabled'=>true, 'depth_w'=>0.2, 'depth_h'=>0.2, 'color'=>array(196,196,196), 'opacity'=>1, 'blend_mode'=>'Normal'));
    $tanggal = date("d F Y", strtotime($penawaran[0]->tanggal));
    $client = $this->global_models->get("crm_market_target", array("id_crm_market_target" => $penawaran[0]->id_crm_market_target));
    $client_to = $client[0]->personnel_first_name." ".$client[0]->personnel_last_name;
    $client_address = $client[0]->personnel_address;
    $client_telp = $client[0]->personnel_telphone;
    $client_fax = $client[0]->personnel_fax;
    $client_email = $client[0]->personnel_email;
    if($client[0]->info_use == 2){
      $client_to = $client[0]->company_title;
      $client_address = $client[0]->company_address;
      $client_telp = $client[0]->company_telphone;
      $client_fax = $client[0]->company_fax;
      $client_email = $client[0]->company_email;
    }
    
    $users = $this->global_models->get("m_users", array("id_users" => $penawaran[0]->create_by_users));
    
    $data = "";
    $no = 1;
    foreach ($items as $itm){
      $data .= '
         <tr>
          <td width="30" align="center">'.$no.'</td>
          <td width="200">'.$itm->products.'</td>
          <td width="200">'.$itm->spesifikasi.'</td>
          <td width="80">'.$itm->qty.'</td>
          <td width="140">Rp. '.number_format($itm->price, 0, ",", ".").'</td>
         </tr>
        ';
          $no++;
    }
    
    $tbl = <<<EOD
            <br />
            <br />
            <br />
            <br />
<table border="0">
 <tr>
  <td width="170">No</td>
  <td width="255">{$penawaran[0]->no}</td>
  <td align="right">{$tanggal}<br /></td>
 </tr>
 <tr>
  <td width="170">To</td>
  <td width="255">{$client_to} <br />
    {$client_address} <br />
    Telp. {$client_telp}<br />
    Fax. {$client_fax}<br />
    Email. {$client_email}<br />
  </td>
  <td align="right"></td>
 </tr>
 <tr>
  <td width="170">Up</td>
  <td width="255">{$penawaran[0]->up}<br /></td>
  <td align="right"></td>
 </tr>
 <tr>
  <td width="170">Subject</td>
  <td width="255">Penawaran Harga</td>
  <td align="right"></td>
 </tr>
</table>
            <br />
            <br />
            Dengan hormat,
            <br />
            <br />
            Dengan ini kami mengajukan penawaran harga barang dengan spesifikasi sebagai berikut:
            <br />
            <br />
            
            <table border="1" cellpadding="2" cellspacing="2">
            <thead>
             <tr>
              <td width="30" align="center"><b>No</b></td>
              <td width="200" align="center"><b>DESCRIPTION</b></td>
              <td width="200" align="center"><b>SPESIFIKASI</b></td>
              <td width="80" align="center"> <b>QTY</b></td>
              <td width="140" align="center"><b>Price<br />(Rp)</b></td>
             </tr>
            </thead>
             {$data}
            </table>
            <br />
            <br />
            <br />
            Note :<br />
            {$penawaran[0]->info}
            <br />
            <br />
            Demikian surat penawaran ini kami buat, atas perhatian dan kerjasamanya kami ucapkan terima kasih.
            <br />
            <br />
            <table border="0">
              <tr>
               <td width="170"></td>
               <td width="255"></td>
               <td align="center">Hormat kami,
               <br />
               <br />
               <br />
               <br />
               <br />
               <u>{$users[0]->name}</u><br />
               {$users[0]->telphone}
                 </td>
              </tr>
             </table>
            <br />
            <br />
            <br />
            <br />
            <br />
            <br />
            <br />
            <br />
            <table border="0">
              <tr>
               <td align="center">
                 <font size="14"><b>PT. MULTI WAHANA MUDA</b></font><br />
            Jl. Cideng Timur No. 11B, Petojo Utara - Jakarta Pusat 10130<br />
            Ph. +6221-6316733, Facs. +6221-6316743 <br />
            E-mail : mwm_promo@yahoo.com
               </td>
              </tr>
             </table>
EOD;

    // Print text using writeHTMLCell()
    $this->mypdf->writeHTML($tbl, true, false, false, false, "");

    // ---------------------------------------------------------

    // Close and output PDF document
    // This method has several options, check the source code documentation for more information.
    $this->mypdf->Output('files/crm/quotation/'.$this->global_models->nicename($penawaran[0]->title."_".$penawaran[0]->create_date).'.pdf', 'F');
  }
  
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */